const axios = require("axios");
const User = require("../models/user");
const RecordList = require("../models/record");

// 查询用户
exports.getUsers = async (req, res) => {
  try {
    const users = await User.find();
    res.status(200).json({
      success: true,
      code: 200,
      data: users,
    });
  } catch (err) {
    res.status(400).json({
      success: false,
      error: err.message,
    });
  }
};
// 创建用户
exports.createUser = async (req, res) => {
  try {
    const users = await User.create(req.body);
    res.status(200).json({
      success: true,
      code: 200,
      token: users.token,
    });
  } catch (err) {
    if (err.code === 11000) {
      return res.status(400).json({
        success: false,
        error: "Duplicate field value",
      });
    }
    res.status(400).json({
      success: false,
      error: err.message,
    });
  }
};

// 查询用户信息
exports.searchUserInfo = async (req, res) => {
  try {
    const { userId } = req.body;
    const records = await RecordList.find({ userId });
    const yearIncome = records.reduce((v, i) => {
      const year = new Date().getFullYear();
      const Iyear = new Date(i.dateTime).getFullYear();
      return year === Iyear ? v + +i.income : v;
    }, 0);
    const monthIncome = records.reduce((v, i) => {
      const year = new Date().getFullYear();
      const Iyear = new Date(i.dateTime).getFullYear();
      const isYear = year === Iyear;
      const month = new Date().getMonth();
      const Imonth = new Date(i.dateTime).getMonth();
      const isMonth = month === Imonth;
      return isYear && isMonth ? v + +i.income : v;
    }, 0);
    // 查询信息
    const users = await User.find({ token: userId });
    console.log(req.body, "🚀 ~ exports.searchUserInfo= ~ users:", users);
    if (!users.length) {
      res.status(200).json({
        success: false,
        code: 200,
        data: {
          list: [],
        },
        message: "没有找到该用户的信息",
      });
    } else {
      res.status(200).json({
        success: true,
        code: 200,
        data: {
          overallRecord: records.length, // 总战绩
          winningRecord: records.filter((item) => item.isWin).length, // 胜率
          cumulativeIncome: records.reduce((v, i) => v + +i.income, 0), // 累计收支
          yearIncome, // 本年收支
          monthIncome, // 本月收支
          list: records,
        },
      });
    }
  } catch (err) {
    res.status(400).json({
      success: false,
      error: err.message,
    });
  }
};

// 获取openId
// 服务端代码（需配置环境变量）

exports.getOpenid = async (req, res) => {
  const APPID = "wxa672b9f8fafb95d5"; // 从环境变量读取
  const SECRET = "3fe620c058d7796eecba7e702620c857";
  const { code } = req.query;
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${code}`;
  try {
    const response = await axios.get(url);
    res.status(200).json({
      message: true,
      code: 200,
      data: response.data,
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      error: error,
    });
  }
};
